package weaver.interfaces.dsjj.duss.docTemplates;

import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.general.BaseBean;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.datasource.DataSource;
import weaver.interfaces.dsjj.duss.TransMethod;
import weaver.interfaces.schedule.BaseCronJob;

import java.io.*;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-07-07
 * @Description: ${description}
 * @ModifyLog:  公文模板同步
 **/

public class DocTempCronJob extends BaseCronJob {
    @Override
    public void execute() {
            BaseBean baseBean = new BaseBean();
            RecordSet rs1 = new RecordSet();
            RecordSet rs2 = new RecordSet();
            baseBean.writeLog("开始同步----DocTempCronJob");
            String docids = "";
            String doccontent = "";
            String userid = "1";
            int docid = -1;
            String time = TransMethod.getTime();
            String timebefore = TransMethod.getTimebefore();
            baseBean.writeLog("timebefore="+timebefore+",curtime="+time);
            Connection conn = null;
            try {
                DataSource ds = (DataSource) StaticObj.getServiceByFullname(("datasource.YaWei"), DataSource.class);
                conn = ds.getConnection();
                String sql = "select guid,userGuid,title,userName,content,createTime from officeTemplates where createTime between ? and ?";
                PreparedStatement pstm = conn.prepareStatement(sql);
                pstm.setString(1, timebefore);
                pstm.setString(2, time);
                ResultSet rs = pstm.executeQuery();
                while (rs.next()) {
                    String guid = Util.null2String(rs.getString("guid"));
                    String userGuid = Util.null2String(rs.getString("userGuid"));
                    String title = Util.null2String(rs.getString("title"));
                    String userName = Util.null2String(rs.getString("userName"));
                    String createTime = Util.null2String(rs.getString("createTime"));
                    Clob clob = rs.getClob("content");
                    rs2.executeQuery("selectcount(*) as counts from qpd_middleinfo where guid='" + guid + "'");
                    rs2.next();
                    int counts = Util.getIntValue(rs2.getString("counts"));
                    if (counts<=0) {
                        String readline = "";
                        StringBuffer sb = new StringBuffer();
                        BufferedReader br = new BufferedReader(clob.getCharacterStream());
                        while ((readline = br.readLine()) != null) {
                            sb = sb.append(readline);
                        }
                        br.close();
                        doccontent = sb.toString();
                        DocServiceImpl docserviceimpl = new DocServiceImpl();
                        DocAttachment[] docattachment = new DocAttachment[1];
                        String filetype = "doc";
                        title = userName + title;
                        DocAttachment da = new DocAttachment();
                        da.setFilename(title);//附件标题
                        da.setFilecontent(doccontent); //附件内容
                        da.setFiletype(filetype); //imagefiletype
                        da.setImagefilename(title);// 附件标题
                        da.setIszip(0);//是否压缩
                        da.setIsAesEncrype(1);//是否加密
                        da.setAesCode("0");
                        da.setIsextfile("1"); //附件是否是office类型

                        if (filetype.equalsIgnoreCase("doc")) {
                            da.setDocfiletype("3");
                        } else if (filetype.equalsIgnoreCase("xls")) {
                            da.setDocfiletype("4");
                        } else if (filetype.equalsIgnoreCase("ppt")) {
                            da.setDocfiletype("5");
                        } else if (filetype.equalsIgnoreCase("wps")) {
                            da.setDocfiletype("6");
                        } else if (filetype.equalsIgnoreCase("docx")) {
                            da.setDocfiletype("7");
                        } else if (filetype.equalsIgnoreCase("xlsx")) {
                            da.setDocfiletype("8");
                        } else if (filetype.equalsIgnoreCase("pptx")) {
                            da.setDocfiletype("9");
                        } else {
                            da.setDocfiletype("2");
                        }
                        docattachment[0] = da;
                        DocInfo doc = new DocInfo(); //创建文档
                        doc.setMaincategory(0);//主目录id
                        doc.setSubcategory(0);//分目录id
                        doc.setSeccategory(131);//子目录id
                        doc.setDocSubject(title);//标题
                        doc.setDoccontent("");//文档内容
                        doc.setAttachments(docattachment);
                        if (!"".equals(userid)) {
                            User user = new User(Util.getIntValue(userid));
                            docid = docserviceimpl.createDocByUser(doc, user);
                            if (docid != -1) {
                                rs1.executeQuery("select filerealpath from imagefile where imagefileid in (select imagefileid from docimagefile where docid in ('" + docid + "'));");
                                rs1.next();
                                String filepath = Util.null2String(rs1.getString("filerealpath"));
                                File file = new File(filepath);
                                baseBean.writeLog("filename:" + file.getName());
                                String srcfilepath = filepath.substring(0, filepath.indexOf('.')) + ".doc";
                                TransMethod.hexToFile(doccontent, srcfilepath);
                                if (file.getName().endsWith(".zip")) {  // zip文件  判断 是否存在
                                    if (file.delete()) {
                                        String newfilepath = filepath.substring(0, filepath.indexOf('.')) + ".zip";
                                        doZip(srcfilepath, newfilepath, 2);
                                    }
                                }

                            }
                            docids += docids == "" ? docid + "" : "," + docid;
                        }
                        rs2.executeUpdate("insert into qpd_middleinfo(guid,userGuid,userName,createTime) values('" + guid + "','" + userGuid + "','" + userName + "','" + createTime + "') ");
                    } else {
                        continue;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                baseBean.writeLog("e:" + e);
            }
            baseBean.writeLog("docids:" + docids);
        rs1.executeUpdate("update syntimedoctemp set beforetime = '"+timebefore+"',curtime='"+time+"' where id ='1'");
    }


    public static File doZip(String sourceDir, String zipFilePath, int needDelSource) {
        BaseBean baseBean = new BaseBean();
        File file = new File(sourceDir);
        File zipFile = new File(zipFilePath);
        ZipOutputStream zos = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        if (!file.exists()) {
            return null;
        }
        try {
            // 创建写出流操作
            os = new FileOutputStream(zipFile);
            bos = new BufferedOutputStream(os);
            zos = new ZipOutputStream(bos);
            String basePath = null;
            // 获取目录
            if (file.isDirectory()) {
                basePath = file.getPath();
            } else {
                basePath = file.getParent();
            }
            zipFile(file, basePath, zos);

        } catch (IOException ex) {
            ex.printStackTrace();
            baseBean.writeLog("IO异常：" + ex.toString());
        } finally {
            try {
                if (needDelSource == 1) {
                    delFolder(sourceDir);
                }
                if (zos != null) {
                    zos.closeEntry();
                    zos.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                baseBean.writeLog("IO异常：" + e.toString());
            }
        }
        return zipFile;
    }

    private static void zipFile(File source, String basePath, ZipOutputStream zos) {
        BaseBean baseBean = new BaseBean();
        File[] files = null;
        if (source.isDirectory()) {
            files = source.listFiles();
        } else {
            files = new File[1];
            files[0] = source;
        }
        InputStream is = null;
        String pathName;
        byte[] buf = new byte[1024];
        int length = 0;
        try {
            for (File file : files) {
                if (file.isDirectory()) {
                    pathName = file.getPath().substring(basePath.length() + 1) + "/";
                    zos.putNextEntry(new ZipEntry(pathName));
                    zipFile(file, basePath, zos);
                } else {
                    pathName = file.getPath().substring(basePath.length() + 1);
                    is = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    zos.putNextEntry(new ZipEntry(pathName));
                    while ((length = bis.read(buf)) > 0) {
                        zos.write(buf, 0, length);
                    }
                    if (bis != null) {
                        bis.close();
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            baseBean.writeLog("IO异常：" + ex.toString());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    baseBean.writeLog("IO异常：" + e.toString());
                }
            }
        }
    }

    public static boolean delFolder(String folderPath) {
        BaseBean baseBean = new BaseBean();
        if (StringUtils.isEmpty(folderPath)) {
            return Boolean.FALSE;
        }
        try {
            delAllFile(folderPath);  //删除完里面所有内容
            File myFilePath = new File(folderPath);
            if (myFilePath.exists()) {
                boolean result = myFilePath.delete();  //删除空文件夹
                //System.out.println( "---------------delete folder ------folderPath:"+folderPath);
                return result;
            }
        } catch (Exception e) {
            baseBean.writeLog("删除文件夹操作出错");
            e.printStackTrace();
            baseBean.writeLog(e.toString());
        }
        return Boolean.FALSE;
    }

    /**
     * 删除文件
     *
     * @param path
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                if (temp.exists()) {
                    temp.delete();
                }
            }
            if (temp.isDirectory()) {
                delAllFile(path + File.separator + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + File.separator + tempList[i]);//再删除空文件夹
            }
        }

    }
}
